<script setup lang="ts">
import { reactive } from 'vue';
import { showToast } from '@tarojs/taro';
import dayjs from 'dayjs';
const props = withDefaults(
  defineProps<{
    modelValue: boolean;
    /**
     * date:日期
     * datetime:日期+时间
     */
    type?: string;
  }>(),
  {
    modelValue: false,
    type: 'date',
  },
);

const emits = defineEmits<{
  (e: 'update:modelValue'): void;
  (e: 'onSelected', startTime: string, endTime: string): void;
}>();

/**
 * 时间筛选
 */
const state = reactive<{
  /**
   * 筛选开始时间
   */
  startTime?: string;
  /**
   * 筛选结束时间
   */
  endTime?: string;
  /**
   * 0没选择开始时间框还是结束时间框
   * 1 开始时间框
   * 2 结束时间框
   */
  currentSelectedTime?: 0 | 1 | 2;
}>({
  startTime: '',
  endTime: '',
  currentSelectedTime: 0,
});

const minDate = dayjs().subtract(8, 'year').toDate();
const maxDate = dayjs().add(8, 'year').toDate();
const currentDate = new Date();
const confirm = ({ selectedValue }) => {
  if (state.currentSelectedTime === 1) {
    if (props.type === 'datetime') {
      const date = selectedValue.slice(0, 3).join('-');
      const time = selectedValue.slice(3).join(':');
      state.startTime = date + ' ' + time;
    } else {
      state.startTime = selectedValue.join('-');
    }
  }

  if (state.currentSelectedTime === 2) {
    if (props.type === 'datetime') {
      const date = selectedValue.slice(0, 3).join('-');
      const time = selectedValue.slice(3).join(':');
      state.endTime = date + ' ' + time;
    } else {
      state.endTime = selectedValue.join('-');
    }
  }

  if (dayjs(state.startTime).isAfter(dayjs(state.endTime))) {
    showToast({
      title: '开始日期不能大于结束日期',
      icon: 'error',
    });
    return;
  }

  if (state.startTime && state.endTime) {
    emits('onSelected', state.startTime, state.endTime);
    emits('update:modelValue');
  }
};
</script>

<template>
  <nut-popup
    position="bottom"
    :visible="props.modelValue"
    @click-overlay="emits('update:modelValue')"
  >
    <nut-date-picker
      v-model="currentDate"
      :type="props.type"
      :min-date="minDate"
      :max-date="maxDate"
      :is-show-chinese="true"
      @confirm="confirm"
      @cancel="emits('update:modelValue')"
    >
      <template v-slot:top>
        <view class="app-time-range-picker-popup__date">
          <nut-input
            placeholder="开始日期"
            type="text"
            v-model="state.startTime"
            @click-input="state.currentSelectedTime = 1"
          /><text>至</text
          ><nut-input
            placeholder="结束日期"
            type="text"
            v-model="state.endTime"
            @click-input="state.currentSelectedTime = 2"
          />
        </view>
      </template>
    </nut-date-picker>
  </nut-popup>
</template>

<style lang="scss">
.app-time-range-picker-popup {
  &__date {
    display: flex;
    justify-content: center;
  }
}
</style>
